package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.dao.MemberDao;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import com.itheima.health.utils.DateUtils;
import com.itheima.health.utils.JedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CheckItemServiceImpl
 * @Description TODO
 * @Author ly
 * @Company 深圳黑马程序员
 * @Date 2019/8/20 16:00
 * @Version V1.0
 */
// dubbo（整合声明式事务处理1：配置applicationContext-tx.xml对类代理，2：@Service(interfaceClass = CheckItemService.class)）
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderDao orderDao;

    @Autowired
    OrderSettingDao orderSettingDao;

    @Autowired
    MemberDao memberDao;

    @Override
    public Result submit(Map map) {
        try {
            // 预约时间
            String orderDate = (String)map.get("orderDate");
            // 将字符串类型转换成日期类型
            Date date = DateUtils.parseString2Date(orderDate);
            //（1）使用预约时间，查询预约设置表，判断是否有该记录
            OrderSetting orderSetting = orderSettingDao.findOrderSettingByOrderDate(date);
            if(orderSetting==null){
                //* 如果没有说明预约设置表没有进行设置，此时不能预约
                return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }else{
                //* 如果有，说明预约可以进行预约，如果预约人数大于等于最大预约数，此时不能预约，提示“预约已满”
                int number = orderSetting.getNumber();
                int reservations = orderSetting.getReservations();
                if(reservations>=number){
                    return new Result(false, MessageConstant.ORDER_FULL);
                }
            }
            // 获取手机号
            String telephone = (String)map.get("telephone");
            // 获取套餐id
            String setmealId = (String)map.get("setmealId");
            //（2）使用手机号，查询会员表，判断当前预约人是否是会员
            Member member = memberDao.findMemberByTelephone(telephone);
            if(member!=null){
                //* 如果是会员：获取会员id，获取预约时间，获取套餐id，查询预约表，如果存在数据，提示“你已经预约当前时间，不能重复预约”
                Integer memberId = member.getId();
                Order paramOrder = new Order(memberId,date,null,null,Integer.parseInt(setmealId));
                List<Order> list = orderDao.findOrderListByOrderCondition(paramOrder);
                // 查询到数据
                if(list!=null && list.size()>0){
                    return new Result(false, MessageConstant.HAS_ORDERED);
                }
            }else{
                // 如果不是会员：注册会员，向会员表中添加数据
                member = new Member();
                member.setName((String)map.get("name"));
                member.setSex((String)map.get("sex"));
                member.setPhoneNumber((String)map.get("telephone"));
                member.setIdCard((String)map.get("idCard"));
                member.setRegTime(new Date()); // 会员注册时间，当前时间
                memberDao.add(member);
            }
            //（3）可以进行预约，更新预约设置表中预约人数的值，使其的值+1
            orderSetting.setReservations(orderSetting.getReservations()+1);
            orderSettingDao.updateReservationsByOrderDate(orderSetting);

            //（4）可以进行预约，向预约表中添加1条数据
            Order order = new Order();
            order.setMemberId(member.getId()); //会员id
            order.setOrderDate(date); // 预约时间
            order.setOrderStatus(Order.ORDERSTATUS_NO); // 预约状态（已到诊/未到诊）
            order.setOrderType((String)map.get("orderType"));
            order.setSetmealId(Integer.parseInt((String)map.get("setmealId")));
            orderDao.add(order);
            return new Result(true, MessageConstant.ORDER_SUCCESS,order);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDER_FAIL);
        }

    }

    @Override
    public  Map findById(Integer id) {
            Map map = orderDao.findById(id);
            if(map!=null){
                Date date = (Date)map.get("orderDate");
                // 将日期转换成字符串
                try {
                    String sDate = DateUtils.parseDate2String(date);
                    map.put("orderDate",sDate);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        return map;
    }
}
